package com.TinyBBS.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.TinyBBS.bean.User;
import com.TinyBBS.db.Config;
import com.TinyBBS.model.UserModel;
import com.TinyBBS.util.Util;

/**
 * Servlet implementation class ChangePassword
 */
public class ChangePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uri = "";
		String error = "";
		if (request.getParameter("passwordsubmit") == null) {
			uri = "views/login.jsp";
		} else {
			HttpSession session = request.getSession();
			String password = request.getParameter("password").trim();
			String repeatpassword = request.getParameter("repeatpassword")
					.trim();
			if (session.getAttribute("emailIdentity") == null) {
				uri = "views/login.jsp";
			} else {
				User user = new User();
				UserModel userM = new UserModel();
				user = userM.getUserByEmail((String) session
						.getAttribute("emailIdentity"));
				if (user != null) {
					if (password.equals(repeatpassword)) {
						String hashedPassword = Util.getHashWithSalt(password, Config.SALT);
						if(userM.updatePassword(hashedPassword,user)){
							error = "Your new password has been commited";
							uri = "views/changeSuccess.jsp";
						}else{
							error = "Unknown Error:";
							uri = "views/changePassword.jsp";
						}
					} else {
						uri = "views/changePassword.jsp";
						error = "Passwords must be same";
					}
				} else {
					uri = "views/changePassword.jsp";
					error = "Unknown Error:";
				}

			}
		}
		request.setAttribute("error", error);
		RequestDispatcher rd = request.getRequestDispatcher(uri);
		rd.forward(request, response);
	}

}
